package com.coderknock.bbs.web.controller

import com.coderknock.bbs.web.response.FileUploadResponse
import com.google.common.io.Files
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.nio.file.Paths
import java.text.SimpleDateFormat
import java.util.*
import javax.servlet.http.Part


/**
 * <p></p>
 * @author 三产
 * @version 1.0
 * @date 2017-11-17
 * @QQGroup 213732117
 * @website http://www.coderknock.com
 * @copyright Copyright 2017 拿客 coderknock.com  All rights reserved.
 * @since JDK 1.8
 */
@RestController
class FileUploadController {
    val dateFormat = SimpleDateFormat("yyyyMMdd")
    @PostMapping("/upload")
    fun handleFormUpload(@RequestParam("file") part: Part): FileUploadResponse {
        //在服务器新建文件
        var filePath = "${dateFormat.format(Date())}/${Date().time}-${part.submittedFileName}"
        var fileAbsoluteFile = "/CoderKnockUpload/$filePath"
        var path = Paths.get(fileAbsoluteFile)
        var file = path.toFile()
        Files.createParentDirs(file)
        file.createNewFile()
        //上传的文件写入到服务器文件中
        part.write(file.absolutePath)
        return FileUploadResponse(data = arrayOf(filePath))
    }
}